define(['require' , 'exports' , 'module' , 'jquery' , 'layer' , 'dmuploader' , 'sortable'] ,
    function (require , exports , module , $ , layer) {

        var message = {
            addLog: function (id, status, str) {
                var d = new Date();
                var li = $('<li />', {'class': 'demo-' + status});

                var message = '[' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '] ';

                message += str;

                li.html(message);

                $(id).prepend(li);
            },

            addFile: function (id, i, file) {
                var url = window.URL || window.webkitURL;
                var imgURL = URL.createObjectURL(file);
                var template = '<div style="overflow: hidden;float: left;height: 186px;margin: 15px 0;" class="col-lg-3" id="demo-file' + i + '">' +
                    '<div class="remove"><i class="icon-remove"></i></div>'+
                    '<img class="goods-imgs" id="img-' + i + '" style="width: 100%;height:100%;" src="'+ imgURL +'">'+
                    '<div style="position: absolute;top: 50%;margin-left: -15px;z-index: 100;" class="col-lg-12">'+
                    '<div class="progress progress-striped active">' +
                    '<div class="progress-bar" role="progressbar" style="width: 0%;">' +
                    '<span class="sr-only">0% Complete</span>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>';

                var itemnum = $(id).attr('file-counter');
                if (!itemnum) {
                    $(id).empty();

                    i = 0;
                }

                i++;

                $(id).attr('file-counter', i);

                $(id).append(template);
            },

            updateFileStatus: function (i, status, message) {
                $('#demo-file' + i).find('span.demo-file-status').html(message).addClass('demo-file-status-' + status);
            },

            updateFileProgress: function (i, percent) {

                $('#demo-file' + i).find('div.progress-bar').width(percent);

                $('#demo-file' + i).find('span.sr-only').html(percent + ' Complete');

            },

            humanizeSize: function (size) {
                var i = Math.floor(Math.log(size) / Math.log(1024));
                return ( size / Math.pow(1024, i) ).toFixed(2) * 1 + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i];
            }
        };

        var upImg = function (num) {
            $('#drag-and-drop-zone').dmUploader({
                url : '/admin/upload/img/goods',
                dataType : 'json',
                fileName : 'imgs',
                allowedTypes : 'image/*',
                onInit: function(){
                    message.addLog('#demo-debug', 'default', 'Plugin initialized correctly');
                },
                onBeforeUpload: function(id){

                    message.addLog('#demo-debug', 'default', 'Starting the upload of #' + id);

                    message.updateFileStatus(id, 'default', 'Uploading...');
                },
                onNewFile: function(id, file){
                    var list = document.getElementById('demo-files').getElementsByTagName('img');
                   // console.log(list);
                    if (list.length >= num ){
                        alert('只允许上传'+num+'张图');
                        return false;
                    }else {
                        message.addFile('#demo-files', id, file);
                    }
                    // if(id >= num){
                    //     alert('只允许上传'+num+'张图');
                    //     return false;
                    //  else {
                    //     message.addFile('#demo-files', id, file);
                    //  }
                },
                onComplete: function(){
                    message.addLog('#demo-debug', 'default', 'All pending tranfers completed');
                },
                onUploadProgress: function(id, percent){
                    var percentStr = percent + '%';

                    message.updateFileProgress(id, percentStr);
                },
                onUploadSuccess: function(id, data){
                    message.addLog('#demo-debug', 'success', 'Upload of file #' + id + ' completed');

                    message.addLog('#demo-debug', 'info', 'Server Response for file #' + id + ': ' + JSON.stringify(data));

                    message.updateFileStatus(id, 'success', 'Upload Complete');

                    message.updateFileProgress(id, '100%');

                    var html = '';

                    if(data.code == 0){
                        $('#img-' + id).attr('src' , data.img_path);
                        html = '<div style="background: #000;text-align: center;color: #fff"><i class="icon-ok-sign"></i>上传成功</div>';
                    }else{
                        html = '<div style="background: #000;text-align: center;color: #fff"><i class="icon-ok-sign"></i>上传成功</div>';
                    }
                    $('#demo-file' + id).find('div.progress').parent().html(html);
                },
                onUploadError: function(id, message){
                    message.updateFileStatus(id, 'error', message);

                    message.addLog('#demo-debug', 'error', 'Failed to Upload file #' + id + ': ' + message);
                },
                onFileTypeError: function(file){
                    message.addLog('#demo-debug', 'error', 'File \'' + file.name + '\' cannot be added: must be an image');
                },
                onFileSizeError: function(file){
                    message.addLog('#demo-debug', 'error', 'File \'' + file.name + '\' cannot be added: size excess limit');
                },
                /*onFileExtError: function(file){
                 message.addLog('#demo-debug', 'error', 'File \'' + file.name + '\' has a Not Allowed Extension');
                 },*/
                onFallbackMode: function(message){
                    message.addLog('#demo-debug', 'info', 'Browser not supported(do something else here!): ' + message);
                }
            });
        };

        var sortImg = function () {
            $('#demo-files').sortable({
                group: 'photo',
                animation: 150
            });
        };

        var removeImg = function () {
            $('#demo-files').on('click' ,'.remove' , function () {
                $(this).parent().remove();
            });
        };


        exports.removeImg = removeImg;
        exports.upImg = upImg;
        exports.sortImg = sortImg;
    });